package com.proton.carepatchtemp.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.RectF;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.activity.AboutProtonActivity;
import com.proton.carepatchtemp.activity.DeviceManagerActivity;
import com.proton.carepatchtemp.activity.FeedBackActivity;
import com.proton.carepatchtemp.activity.HealthTipsActivity;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.base.BaseFragment;
import com.proton.carepatchtemp.base.MyDialogFragment;
import com.proton.carepatchtemp.ble.BleManager;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Config;
import com.proton.carepatchtemp.constant.DialogCodes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.constant.Settings;
import com.proton.carepatchtemp.database.TestManager;
import com.proton.carepatchtemp.ui.BadgeView;
import com.proton.carepatchtemp.ui.HighLight.HighLight;
import com.proton.carepatchtemp.ui.SwitchView;
import com.proton.carepatchtemp.utils.FileUtils;
import com.proton.carepatchtemp.utils.FormatUtils;
import com.proton.carepatchtemp.utils.NetUtils;
import com.proton.carepatchtemp.utils.SpUtils;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.pedant.SweetAlert.Type;
import cn.qqtheme.framework.picker.OptionPicker;

import static com.proton.carepatchtemp.constant.Config.WARNING_DIV_DEFAULT;

public class SettingFragment extends BaseFragment implements MyDialogFragment.OnDialogListener {
    //创建单例
    private static volatile SettingFragment sInst = null;  // <<< 这里添加了 volatile
    List<File> files = new ArrayList<File>();
    private View rootView;
    private OptionPicker mTimePicker;
    /**
     * 摄氏度℃
     */
    private TextView mTvCentigrade;
    /**
     * 华氏度℉
     */
    private TextView mTvFahrenheit;
    private LinearLayout mLnlDeviceManager;
    private ImageView mSettingMsgArrow;
    private LinearLayout mLnlMsgSetting;
    /**
     * 15分钟
     */
    private TextView mTvWarningTimeDiv;
    private RelativeLayout mRtlWarningTime;
    private SwitchView mSvLowPower;
    private SwitchView mSvHighWarning;
    private SwitchView mSvLowWarning;
    private SwitchView mSvDisconnectWarning;
    private SwitchView mSvShareNtf;
    private SwitchView mSvReportCreated;
    private LinearLayout mLnlMsgSettingMenu;
    private LinearLayout mLnlDeleteCache;
    private LinearLayout mSettingAboutProton;
    private LinearLayout mSettingExit;
    private LinearLayout mSettingQQ;
    private long size = 0;
    /**
     * 12M
     */
    private TextView mTvFoldersSize;
    private ImageView mUserQqGroup;
    private LinearLayout mLnlUseDirection;
    private LinearLayout mLnlFeedBack;
    private BadgeView badge;
    private ImageView mIvDeviceManager;
    private LinearLayout mLnlSettingTips;

    public SettingFragment() {
        // Required empty public constructor
    }

    public static SettingFragment getSettingFragment() {
        Bundle args = new Bundle();
        SettingFragment inst = sInst;  // <<< 在这里创建临时变量
        if (inst == null) {
            synchronized (SettingFragment.class) {
                inst = sInst;
                if (inst == null) {
                    inst = new SettingFragment();
                    sInst = inst;
                }
            }
        }
        inst.setArguments(args);
        return inst;  // <<< 注意这里返回的是临时变量
    }

    @Override
    public void dealEvent(MainEvent event) {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTimePicker = new OptionPicker(getActivity(), Settings.arrayTimes);
        mTimePicker.setTitleText(R.string.test_time);
        mTimePicker.setOffset(2);//偏移量
        mTimePicker.setSelectedItem(FormatUtils.formatTime(SpUtils.getLong(Extras.WARNING_TIME_DIV, WARNING_DIV_DEFAULT)));
        mTimePicker.setLabel(null);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_setting, container, false);
        initView(rootView);
        initData();
        setListener();
        return rootView;
    }

    private void initData() {
        mSvLowPower.setOpened(SpUtils.getBoolean(Extras.SETTING_LOW_POWER, Config.LOW_POWER_WARNING_DEFAULT));
        mSvHighWarning.setOpened(SpUtils.getBoolean(Extras.SETTING_HIGH_TEMP_WARNING, Config.HIGH_TEMP_WARNING_DEFAULT));
        mSvLowWarning.setOpened(SpUtils.getBoolean(Extras.SETTING_LOW_TEMP_WARNING, Config.LOW_TEMP_WARNING_DEFAULT));
        mSvDisconnectWarning.setOpened(SpUtils.getBoolean(Extras.SETTING_DEVICE_DISC_WARNING, Config.DEVICE_DISCONNECT_WARNING_DEFAULT));
        mSvShareNtf.setOpened(SpUtils.getBoolean(Extras.SETTING_DEVICE_SHARE_NTF, Config.DEVICE_SHARE_NOTIFICATION_DEFAULT));
        mSvReportCreated.setOpened(SpUtils.getBoolean(Extras.SETTING_REPORT_CREATED_NTF, Config.REPORT_CREATED_NOTIFICATION_DEFAULT));
        if (Config.TEMP_UNIT_C == SpUtils.getInt(Extras.TEMP_UNIT, Config.TEMP_UNIT_DEFAULT)) {
            mTvCentigrade.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), R.mipmap.checked), null, null, null);
            mTvFahrenheit.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), R.mipmap.unchecked), null, null, null);
        } else if (Config.TEMP_UNIT_F == SpUtils.getInt(Extras.TEMP_UNIT, Config.TEMP_UNIT_DEFAULT)) {
            mTvCentigrade.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), R.mipmap.unchecked), null, null, null);
            mTvFahrenheit.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), R.mipmap.checked), null, null, null);
        }
        mTvWarningTimeDiv.setText(FormatUtils.formatTime(TestManager.getAlarmInterval()));
    }


    /**
     * 设置监听器
     */
    private void setListener() {
        mTvCentigrade.setOnClickListener(v -> {
            mTvCentigrade.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), R.mipmap.checked), null, null, null);
            mTvFahrenheit.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), R.mipmap.unchecked), null, null, null);
            SpUtils.saveInt(Extras.TEMP_UNIT, Config.TEMP_UNIT_C);
            EventBus.getDefault().post(new MainEvent(Codes.SETTING_TEMP_UNIT_C));
        });

        mTvFahrenheit.setOnClickListener(v -> {
            mTvCentigrade.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), R.mipmap.unchecked), null, null, null);
            mTvFahrenheit.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), R.mipmap.checked), null, null, null);
            SpUtils.saveInt(Extras.TEMP_UNIT, Config.TEMP_UNIT_F);
            EventBus.getDefault().post(new MainEvent(Codes.SETTING_TEMP_UNIT_F));
        });

        //  设置控件点击监听器
        mLnlDeviceManager.setOnClickListener(view -> {
            TastyUtils.makeTextShort(R.string.device_config, TastyToast.DEFAULT);
        });

        //  设备管理
        mLnlDeviceManager.setOnClickListener(view -> {
            Intent goDeviceManager = new Intent(getActivity(), DeviceManagerActivity.class);
            getActivity().startActivity(goDeviceManager);
        });

        //  报警间隔时长设置
        mRtlWarningTime.setOnClickListener(v -> {
            try {
                if (mTimePicker != null) {
                    mTimePicker.show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        //  消息设置菜单展开控制
        mLnlMsgSetting.setOnClickListener(view -> {
            if (View.GONE == mLnlMsgSettingMenu.getVisibility()) {
                mLnlMsgSettingMenu.setVisibility(View.VISIBLE);
                mSettingMsgArrow.setImageResource(R.mipmap.setting_arrow_on);
            } else {
                mLnlMsgSettingMenu.setVisibility(View.GONE);
                mSettingMsgArrow.setImageResource(R.mipmap.setting_arrow_off);
                mTvWarningTimeDiv.setText(FormatUtils.formatTime(TestManager.getAlarmInterval()));
            }
        });
        //  意见反馈
        mLnlFeedBack.setOnClickListener(v -> {
            Intent goFeedBack = new Intent(getActivity(), FeedBackActivity.class);
            startActivity(goFeedBack);
        });
        //  关于质子
        mSettingAboutProton.setOnClickListener(view -> {
            Intent goAboutProtonActivity = new Intent(getActivity(), AboutProtonActivity.class);
            startActivity(goAboutProtonActivity);
        });

        mLnlSettingTips.setOnClickListener(v -> {
            Intent goHealthTips = new Intent(getActivity(), HealthTipsActivity.class);
            goHealthTips.putExtra(Extras.MSG_HEALTH_TIPS_URL, "http://www.protontek.com/attention/android.html");
            goHealthTips.putExtra(Extras.WEB_TITLE, getResources().getString(R.string.string_matters_need_attention));
            startActivity(goHealthTips);
        });

        //  退出登录
        mSettingExit.setOnClickListener(view -> {
            LogUtils.e("Loginout is called ");
            try {
                new SweetAlertDialog(getActivity(), Type.WARNING_TYPE)
                        .setTitleText(getString(R.string.string_confirm_exit))
                        .setContentText(getString(R.string.string_confirm_exit_warm))
                        .setCancelText(getString(R.string.string_cancel))
                        .setConfirmText(getString(R.string.string_confirm))
                        .showCancelButton(true)
                        .setCancelClickListener(sDialog -> {
                            // reuse previous dialog instance, keep widget user state, reset them if you need
                            sDialog.dismiss();

                            // or you can new a SweetAlertDialog to show
                           /* sDialog.dismiss();
                            new SweetAlertDialog(SampleActivity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("Cancelled!")
                                    .setContentText("Your imaginary file is safe :)")
                                    .setConfirmText("OK")
                                    .show();*/
                        })
                        .setConfirmClickListener(sDialog -> {
                            sDialog.dismiss();
                            VCare.get().logout();
                            new AsyncTask<Void, Void, Void>() {
                                @Override
                                protected void onPreExecute() {
                                    sDialog.setTitleText(getString(R.string.string_exiting_login))
                                            .showCancelButton(false)
                                            .setCancelClickListener(null)
                                            .setConfirmClickListener(null)
                                            .changeAlertType(Type.PROGRESS_TYPE);
                                    super.onPreExecute();
                                }

                                @Override
                                protected Void doInBackground(Void... params) {
                                    if (NetUtils.hasNet()) {
                                        XMPPTCPConnection conn = VCare.get().getXmppConnection();
                                        if (conn != null) {
                                            conn.disconnect();
                                            LogUtils.d("XMPPTCPConnection disconnecting!");
                                            VCare.get().closeConnection();
                                        }
                                    }

                                    BleManager.get().closeAll();
                                    return null;
                                }

                                @Override
                                protected void onPostExecute(Void aVoid) {
                                    super.onPostExecute(aVoid);
                                    size = 0;
                                    mTvFoldersSize.setText("0.00KB");
                                    LogUtils.e("LOGIN_OUT");
                                }
                            }.execute();
                        })
                        .show();

            } catch (Throwable throwable) {
            }

        });


        mTimePicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                mTvWarningTimeDiv.setText(item);
                SpUtils.saveLong(Extras.WARNING_TIME_DIV, (long) 15 * (index + 1) * 60 * 1000);
                LogUtils.d(item + "       " + TestManager.getAlarmInterval());
            }
        });

        mLnlDeleteCache.setOnClickListener(v -> {

            try {
                new SweetAlertDialog(getActivity(), Type.WARNING_TYPE)
                        .setTitleText(getString(R.string.string_confirm_delete))
//                        .setContentText("Won't be able to recover this file!")
                        .setCancelText(getString(R.string.string_cancel))
                        .setConfirmText(getString(R.string.string_delete))
                        .showCancelButton(true)
                        .setCancelClickListener(Dialog::dismiss)
                        .setConfirmClickListener(sDialog -> {

                            new AsyncTask<Void, Void, Void>() {
                                @Override
                                protected void onPreExecute() {
                                    sDialog.setTitleText("Deleting!")
                                            .showCancelButton(false)
                                            .setCancelClickListener(null)
                                            .setConfirmClickListener(null)
                                            .changeAlertType(Type.PROGRESS_TYPE);
                                    super.onPreExecute();
                                }

                                @Override
                                protected Void doInBackground(Void... params) {
                                    for (File f :
                                            files) {
                                        if (null != VCare.get().getFirmWare() && f.getName().equalsIgnoreCase(VCare.get().getFirmWare().getVersion())) {
                                            continue;
                                        }
                                        FileUtils.deleteFolderFile(f, true);
                                    }
                                    return null;
                                }

                                @Override
                                protected void onPostExecute(Void aVoid) {
                                    super.onPostExecute(aVoid);
                                    size = 0;
                                    mTvFoldersSize.setText("0.00KB");

                                    sDialog.setTitleText(getString(R.string.string_delete))
                                            .setContentText(getString(R.string.string_cache_file_deleted))
                                            .setConfirmText("OK")
                                            .showCancelButton(false)
                                            .setCancelClickListener(null)
                                            .setConfirmClickListener(null)
                                            .changeAlertType(Type.SUCCESS_TYPE);

                                }
                            }.execute();

                        })

                        .show();
            } catch (Throwable throwable) {
                // TODO: 2017/3/27 未知原因会抛出异常（WindowManager$BadTokenException）
            }


        });

        mSvLowPower.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn(SwitchView view) {
                view.toggleSwitch(true);
                SpUtils.saveBoolean(Extras.SETTING_LOW_POWER, true);
            }

            @Override
            public void toggleToOff(SwitchView view) {
                view.toggleSwitch(false);
                SpUtils.saveBoolean(Extras.SETTING_LOW_POWER, false);
            }
        });

        mSvHighWarning.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn(SwitchView view) {
                view.toggleSwitch(true);
                SpUtils.saveBoolean(Extras.SETTING_HIGH_TEMP_WARNING, true);
            }

            @Override
            public void toggleToOff(SwitchView view) {
                view.toggleSwitch(false);
                SpUtils.saveBoolean(Extras.SETTING_HIGH_TEMP_WARNING, false);
            }
        });

        mSvLowWarning.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn(SwitchView view) {
                view.toggleSwitch(true);
                SpUtils.saveBoolean(Extras.SETTING_LOW_TEMP_WARNING, true);
            }

            @Override
            public void toggleToOff(SwitchView view) {
                view.toggleSwitch(false);
                SpUtils.saveBoolean(Extras.SETTING_LOW_TEMP_WARNING, false);
            }
        });

        mSvDisconnectWarning.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn(SwitchView view) {
                view.toggleSwitch(true);
                SpUtils.saveBoolean(Extras.SETTING_DEVICE_DISC_WARNING, true);
            }

            @Override
            public void toggleToOff(SwitchView view) {
                view.toggleSwitch(false);
                SpUtils.saveBoolean(Extras.SETTING_DEVICE_DISC_WARNING, false);
            }
        });

        mSvShareNtf.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn(SwitchView view) {
                view.toggleSwitch(true);
                SpUtils.getBoolean(Extras.SETTING_DEVICE_SHARE_NTF, true);
            }

            @Override
            public void toggleToOff(SwitchView view) {
                view.toggleSwitch(false);
                SpUtils.getBoolean(Extras.SETTING_DEVICE_SHARE_NTF, false);
            }
        });

        mSvReportCreated.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn(SwitchView view) {
                view.toggleSwitch(true);
                SpUtils.getBoolean(Extras.SETTING_REPORT_CREATED_NTF, true);
            }

            @Override
            public void toggleToOff(SwitchView view) {
                view.toggleSwitch(false);
                SpUtils.getBoolean(Extras.SETTING_REPORT_CREATED_NTF, false);
            }
        });

        mLnlUseDirection.setOnClickListener(v -> {
            Intent goHealthTips = new Intent(getContext(), HealthTipsActivity.class);
            goHealthTips.putExtra(Extras.MSG_HEALTH_TIPS_URL, "http://www.protontek.com/APP-Help/carePath-temp.html");
            goHealthTips.putExtra(Extras.WEB_TITLE, "帮助");
            startActivity(goHealthTips);
        });
        mSettingQQ.setOnClickListener(view -> {
            if (!joinQQGroup(Settings.QQ_GROUP)) {
                TastyUtils.makeTextShort(R.string.hava_no_qq, TastyToast.DEFAULT);
            }
        });

    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            size = 0;
            new AsyncTask<Void, Void, Long>() {
                @Override
                protected Long doInBackground(Void... params) {
                    File file = new File(FileUtils.getJson_filepath());
                    File file1 = new File(FileUtils.getJson_fir());
                    File file2 = new File(FileUtils.getJson_sec());
                    File file3 = new File(FileUtils.getPdf());
                    File file4 = new File(FileUtils.getFirmWare());
                    File file5 = new File(FileUtils.getCarePatchLog());
                    File file6 = new File(FileUtils.getTemp());
                    files.clear();
                    files.add(file);
                    files.add(file1);
                    files.add(file2);
                    files.add(file3);
                    files.add(file4);
                    files.add(file5);
                    files.add(file6);
                    for (File f :
                            files) {
                        size += FileUtils.getFolderSize(f);
                    }
                    return size;
                }

                @Override
                protected void onPostExecute(Long aLong) {
                    if (mTvFoldersSize != null) {
                        mTvFoldersSize.postDelayed(() -> {
                            mTvFoldersSize.setText(FileUtils.getFormatSize(aLong));
                            setBadge();
                        }, 500);
                    }
                    super.onPostExecute(aLong);
                }
            }.execute();
        }
    }

    private void setBadge() {
        badge = new BadgeView(getActivity());
        badge.setScaleX(0.5F);
        badge.setScaleY(0.5f);
        badge.setTargetView(mIvDeviceManager);
        badge.setTextColor(Color.RED);
        badge.setBadgeCount(1);
        if (VCare.get().needUpdate <= 0) {
            badge.setVisibility(View.GONE);
        } else {
            badge.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public void showHighLight() {

        HighLight highLight = new HighLight(getActivity())
                .anchor(getView().findViewById(R.id.ll_settings)) //绑定根布局，在Activity中可不写
                .setIntercept(true) // 查看注释和代码，可设置其他属性
                .setIsNeedBorder(false)
                .setShadow(true)
                .addHighLight(R.id.lnl_use_direction, R.layout.left_top_help, new HighLight.OnPosCallback() {
                    @Override
                    public void getPos(float rightMargin, float bottomMargin, RectF rectF, HighLight.MarginInfo marginInfo) {

                        marginInfo.leftMargin = rectF.left + rectF.width() / 5;
                        marginInfo.topMargin = rectF.bottom;

                    }
                });
        highLight.show();

        highLight.setChildOnClickListener(R.id.iv_next_step, v -> {
            highLight.remove();
        });

    }

    private void initView(View rootView) {
        mTvCentigrade = rootView.findViewById(R.id.tv_centigrade);
        mTvFahrenheit = rootView.findViewById(R.id.tv_fahrenheit);
        mLnlDeviceManager = rootView.findViewById(R.id.lnl_device_manager);
        mSettingMsgArrow = rootView.findViewById(R.id.setting_msg_arrow);
        mLnlMsgSetting = rootView.findViewById(R.id.lnl_msg_setting);
        mTvWarningTimeDiv = rootView.findViewById(R.id.tv_warning_time_div);
        mRtlWarningTime = rootView.findViewById(R.id.rtl_warning_time);
        mSvLowPower = rootView.findViewById(R.id.sv_low_power);
        mSvHighWarning = rootView.findViewById(R.id.sv_high_warning);
        mSvLowWarning = rootView.findViewById(R.id.sv_low_warning);
        mSvDisconnectWarning = rootView.findViewById(R.id.sv_disconnect_warning);
        mSvShareNtf = rootView.findViewById(R.id.sv_share_ntf);
        mSvReportCreated = rootView.findViewById(R.id.sv_report_created);
        mLnlMsgSettingMenu = rootView.findViewById(R.id.lnl_msg_setting_menu);
        mLnlDeleteCache = rootView.findViewById(R.id.lnl_delete_cache);
        mSettingAboutProton = rootView.findViewById(R.id.setting_about_proton);
        mSettingExit = rootView.findViewById(R.id.setting_exit);
        mSettingQQ = rootView.findViewById(R.id.lnl_user_qq_group);
        mTvFoldersSize = rootView.findViewById(R.id.tv_folders_size);
        mUserQqGroup = rootView.findViewById(R.id.user_qq_group);
        mLnlUseDirection = rootView.findViewById(R.id.lnl_use_direction);
        mLnlFeedBack = rootView.findViewById(R.id.lnl_feed_back);
        mIvDeviceManager = rootView.findViewById(R.id.iv_device_manager);
        mLnlSettingTips = rootView.findViewById(R.id.lnl_setting_tips);

        if (VCare.isInternal) {
            mLnlUseDirection.setVisibility(View.GONE);
            rootView.findViewById(R.id.id_help_divder).setVisibility(View.GONE);

            mLnlSettingTips.setVisibility(View.GONE);
            rootView.findViewById(R.id.id_attention_divider).setVisibility(View.GONE);

            mSettingQQ.setVisibility(View.GONE);
            rootView.findViewById(R.id.id_qq_divider).setVisibility(View.GONE);
        }
    }

    /****************
     * 发起添加群流程。群号：卡帕奇体温贴用户群1(517778251) 的 key 为： 0Xt2-CdDomqPGIE6fYr_IzYo5aqe0fDJ
     * 调用 joinQQGroup(0Xt2-CdDomqPGIE6fYr_IzYo5aqe0fDJ) 即可发起手Q客户端申请加群 卡帕奇体温贴用户群1(517778251)
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回fals表示呼起失败
     ******************/
    public boolean joinQQGroup(String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }

    @Override
    public void onDialogClick(int requestCode, int result) {
        switch (requestCode) {
            case DialogCodes.DELETE_CACHE:
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        for (File f :
                                files) {
                            if (null != VCare.get().getFirmWare() && f.getName().equalsIgnoreCase(VCare.get().getFirmWare().getVersion())) {
                                continue;
                            }
                            FileUtils.deleteFolderFile(f, true);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        size = 0;
                        mTvFoldersSize.setText("0.00KB");
                    }
                }.execute();
                break;
            case DialogCodes.LOGIN_OUT:
                LogUtils.e("LOGIN_OUT");
                VCare.get().logout();
                break;
        }
    }
}
